<template>
  <div class="stats-panel">
    <div class="stats-panel-head stats-form">
      <h3 class="stats-map">
        <span>{{$t('report.statistics.title33')}}</span>
        <div class="stats-form-group stats-checkbox refresh-checkbox">          
          <el-popover trigger="hover">
            <div>{{$t('report.staffView.tip1')}}</div>                
            <base-checkbox slot="reference" :value="isRefresh" @input="changeRefresh">{{$t('report.staffView.tip2')}}</base-checkbox>     
          </el-popover>
        </div>      
      </h3>     
      <!-- <div class="stats-form-group">
        <select @change="chooseTeam">
          <option value="">全部</option>
          <option v-for="team in teams" :key="team.id" :value="team.id">{{team.name}}</option>
        </select>
      </div> -->

      <biz-team-select class="stats-team-select biz-team-select" is-auto-select-child collapse multiple :value="tag" @input="chooseTeam" :fetch-func="fetchTeam"/>

      <el-select v-model="department" clearable :placeholder="$t('common.task.angle.all')" multiple @change="taskType" class="task-type">
        <el-option
          v-for="item in departmentList"
          :key="item.value"
          :label="item.label"
          :value="item.value">
        </el-option>
      </el-select>
        
      <el-popover trigger="hover">
        <ul>
          <i18n path="report.staffView.tip6" tag="li">
            <kbd place="keyName">ESC</kbd>
          </i18n>
          <li>{{$t('report.staffView.tip4')}}</li>
          <li>{{$t('report.staffView.tip5')}}</li>
        </ul>

        <button slot="reference" type="button" class="stats-fullscreen-btn" @click="fullScreen">
          <i class="iconfont icon-fangda"></i>
        </button>
      </el-popover>
    </div>
    <div class="stats-panel-body stats-plan-map-wrap" ref="mapWrap">
      <div id="map"></div>
      <div class="stats-plan-list" v-if="taskList.length > 0">
        <div class="stats-plan-list-head">
          <h3>{{$t('common.label.taskList')}}</h3>
          <button type="button" @click="close">
            <i class="iconfont icon-fe-close"></i>
          </button>
        </div>
        <div class="stats-plan-list-body">
          <div class="stats-plan-map-task" v-for="task in taskList" :key="task.id">
            <el-tooltip :content="$t('report.product.title11')" placement="top" v-if="task.isGuideData">
              <div class="superscript"></div>
            </el-tooltip>
            <div class="stats-plan-row" :class="task.isGuideData ? 'sample-tooltip-content-padding' : ''"> 
              <div class="stats-plan-row-left">{{$t('common.label.taskNo')}}：</div>
              <div class="stats-plan-row-right">{{task.taskNo}}</div>
            </div>
            <div class="stats-plan-row"> 
              <div class="stats-plan-row-left">{{$t('common.label.taskTemplate')}}：</div>
              <div class="stats-plan-row-right">{{task.templateName}}</div>
            </div>
            <div class="stats-plan-row"> 
              <div class="stats-plan-row-left">{{$t('common.customer.customerName')}}：</div>
              <div class="stats-plan-row-right">{{task.customerName}}</div>
            </div>
            <div class="stats-plan-row"> 
              <div class="stats-plan-row-left">{{$t('product.detail.catalogView.type.linkman')}}：</div>
              <div class="stats-plan-row-right">{{task.lmName}}</div>
            </div>
            <div class="stats-plan-row"> 
              <div class="stats-plan-row-left">{{$t('common.base.phone')}}：</div>
              <div class="stats-plan-row-right">{{task.lmPhone}}</div>
            </div>
            <div class="stats-plan-row"> 
              <div class="stats-plan-row-left">{{$t('common.base.locationMap.address')}}：</div>
              <div class="stats-plan-row-right">{{task.customerAddress | prettyAddress}}</div>
            </div>
            <div class="stats-plan-row"> 
              <div class="stats-plan-row-left">{{$t('common.form.type.planTime')}}：</div>
              <div class="stats-plan-row-right">{{task.planTime | fmt | fmt_16}}</div>
            </div>
            <div class="stats-plan-row"> 
              <div class="stats-plan-row-left">{{$t('common.task.flow.planStartTime')}}：</div>
              <div class="stats-plan-row-right">{{task.planStartTime | fmt | fmt_16}}</div>
            </div>
            <div class="stats-plan-row"> 
              <div class="stats-plan-row-left">{{$t('common.task.flow.planFinishTime')}}：</div>
              <div class="stats-plan-row-right">{{task.planEndTime | fmt | fmt_16}}</div>
            </div>
            <div class="stats-plan-row"> 
              <div class="stats-plan-row-left">{{$t('common.base.status')}}：</div>
              <div class="stats-plan-row-right">
                <span class="stats-badge" :style="{backgroundColor: stateColor(task)}">{{task.state | taskStateName}}</span> 
                <a href="#" class="pull-right" @click="openTask($event,task)">{{ $t('common.base.view') }}</a>
              </div>
            </div>
          </div>
        </div>     
      </div>
    </div>
  </div>
</template>

<script>
import { t } from '@src/locales';
/* global AMap*/
import * as DomUtil from 'src/util/dom/index';
import http from 'src/util/HttpUtil';

import BaseCheckbox from 'packages/BaseCheckbox.vue';
import TaskStateEnum from '@model/enum/TaskStateEnum';
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
let map = null; 
let clusterer = null;
let t1;

function generateKey(lng, lat){
  return `lng_${lng}_lat_${lat}`;
}

function timeChunk(arr, num, callback) {
  let delay = 25; 
  let timer = null;
  let _resolve = null;
  let _reject = null; // eslint-disable-line

  function done(){
    if(arr.length > 0) return invoke(arr);

    clearTimeout(timer);
    _resolve();
  }

  function invoke(arr){
    timer = setTimeout(function(){
      let data = arr.length > num ? arr.splice(0, num) : arr.splice(0);
      callback(data, done);
    }, delay);
  }

  return new Promise((resolve, reject) => {
    _resolve = resolve;
    _reject = reject;

    invoke(arr);
  });
}

export default {
  name: 'plan-map',
  props: {
    chartType: {
      type: String,
      default: ''
    }
  },
  data(){
    return {
      tag: [],
      taskMap: {},
      taskList: [],
      // teams: [],
      teamId: [],
      department: [], // 选择的工单
      departmentList: [{value: 1, label: t('common.label.unfinishTask')}, {value: 2, label: t('report.common.taskState.0')}], // 工单列表
      isRefresh:false
    }
  },
  methods: {
    // 选择工单
    async taskType() {
      let instance = this.$loading.show(this.$el)
      let data = await this.fetchData();
      this.renderMap(data);

      instance.hide();
    },
    fetchTeam(params){
      return http.post('/security/tag/tree', {...params, ...{authKey: 'VIP_REPORT_VIEW'}})
    },
    changeRefresh(value){  
      this.isRefresh = value;
      if(!this.isRefresh) return clearInterval(t1);   
      t1 = setInterval(() => {
        this.refreshMap();
      }, 300000);      
    },
    async refreshMap(){
      try {          
        let instance = this.$loading.show(this.$el)
        let data = await this.fetchData();
        this.renderMap(data);

        instance.hide();
      } catch (error) {
        console.log(error)
      }
    },
    async chooseTeam(value){
      try { 
        this.$emit('trackEvent', 'chooseTeam');
        
        // let tag = (Array.isArray(value) ? value[0] : value) || {};
        let tag = value;
        this.tag = value;
        this.teamId = tag.map(item => {return item.id});
        
        let instance = this.$loading.show(this.$el)
        let data = await this.fetchData();
        this.renderMap(data);

        instance.hide();
      } catch (error) {
        console.log(error)
      }

      this.chartType && this.$track.commonFn.chartTrack(this.chartType, 'REPORT_SEARCH_TEAM', this.$track)
    },
    fullScreen(){
      if(this.$platform.inDingTalk()) return;
      DomUtil.fullScreen(this.$refs.mapWrap);
    },
    async renderMap(data = []){
      if(clusterer) {
        clusterer.clearMarkers();
        map.clearMap();
      }
      
      this.taskMap = {};
      data = data.filter(item => {
        let {longi, lati} = item || {};
        return longi && lati;
      });

      data.forEach(item => {
        let {longi, lati} = item || {};
        let key = generateKey(longi, lati);
        if(!this.taskMap[key]) this.taskMap[key] = [];
        this.taskMap[key].push(item)
      })

      let markers = [];
      let createMarker = this.createMarker;
      
      await timeChunk(data, 500, function(chunk, done){
        // 创建marker
        for(let i = 0; i < chunk.length; i++){
          markers.push(createMarker(chunk[i]))
        }

        done();
      })

      // 创建cluster
      let count = markers.length;
      clusterer = new AMap.MarkerClusterer(map, markers, {
        maxZoom: 12,
        averageCenter:true,
        renderCluserMarker: context => this.renderCluserMarker(count, context)
      });
    },
    renderCluserMarker(count, context){
      // let factor = Math.pow(context.count / count, 1 / 18);
      let size = Math.round(10 + Math.pow(context.count / count, 1 / 5) * 30);

      let div = document.createElement('div');
      // var Hue = 180 - factor * 180;

      div.style.width = div.style.height = div.style.lineHeight = `${size }px`;

      div.className = 'plan-map-cluser ripple';
      div.innerHTML = `<span>${context.count}</span>`;

      context.marker.setOffset(new AMap.Pixel( -size / 2, -size / 2));
      context.marker.setContent(div)
    },
    createMarker(data){
      let {longi, lati} = data || {};

      let marker = new AMap.Marker({
        position: [longi, lati],
        extData: data,
        content: '<div class="plan-map-marker"></div>'
      });

      marker.on('click', event => {
        let extData = marker.getExtData();
        let {longi, lati} = extData || {};
        let key = generateKey(longi, lati);
        this.getTaskMapList(this.taskMap[key].map(item => {return item.taskNo}))
      })
      return marker;
    },
    // 获取详细列表
    async getTaskMapList(taskNoList) {
      const {list} = await http.post('/api/report/outside/stats/plan/getTaskMapList', {taskNoList})
      this.taskList = list || [];
    },

    async initMap() {
      try {
        map = new AMap.Map('map', {
          resizeEnable: true,
          center:[105, 34],
          zoom: 4,
          zooms: [4, 18]
        });

        let microTask = [];

        microTask.push(this.fetchData());
        microTask.push(new Promise((resolve, reject) => {
          map.plugin(['AMap.MarkerClusterer'], () => resolve(true));
        }));
        
        let instance = this.$loading.show(this.$el)
        let result = await Promise.all(microTask);

        this.renderMap(result[0])
        instance.hide();
      } catch (error) {
        console.log(error)
      }
    },
    loadMap() {
      let callback = '_amap_callback_stats_plan_dongls_0111';
      let url = `https://webapi.amap.com/maps?v=1.3&key=3cf1b829475ac81c406ceca9ec57d73d&callback=${ callback}`;
      window[callback] = () => {
        setTimeout(() => this.initMap(), 100);
      };

      DomUtil.importScript(url).catch(err => console.log(err));
    },
    fetchData(){
      let taskStatusType = !this.department.length || this.department.length > 1 ? 0 : this.department[0];
      let params = {
        tagIds: this.teamId,
        taskStatusType,
      };
      return http.post('/api/report/outside/stats/plan/unFinishedTask', params)
    },
    openTask(event, task){
      event.preventDefault();
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `taskView_${ task.id}`, 
      //   title: `工单${task.taskNo}`,
      //   close: true, 
      //   url: `/task/view/${ task.id}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: task.id,
        titleKey: task.taskNo,
        fromId
      })
    },
    close(){
      this.taskList = [];
    },
    stateColor(task){
      return TaskStateEnum.getColor(task.state);
    }
  },
  mounted(){
    // let initData = JSON.parse(JSON.stringify(window._init_data)) || {};

    // this.teams = initData.teams || []

    // 加载地图
    // setTimeout(() => this.loadMap(), 2000)
    this.$nextTick(()=>{
      this.initMap()
    })
  },
  components: {
    [BaseCheckbox.name]: BaseCheckbox
  }
}
</script>

<style lang="scss" scoped>
.task-type {
  border: 1px solid #e0e1e2;
  margin:0 10px;
}
</style>
<style lang="scss">
#map {
  width: 100%;
  height: 100%;
  min-height: calc(100vh - 78px);
}
.stats-map{
  display:flex;
  .refresh-checkbox{
    margin-left:20px;
  }
}

.plan-map-marker{
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 3px solid #fff;
  background-color: #c41d7f;
  box-shadow: 1px 1px 8px rgba(0,0,0, .35);
}

.stats-plan-list{
  position: absolute;
  top: 10px;
  right: 10px;
  width: 240px;
  background-color: #fff;
  box-shadow: 0 2px 2px rgba(0,0,0,.15);
  border-radius: 2px;
}


.stats-plan-list-head{
  height: 31px;
  border-bottom: 1px solid #d5d5d5;

  display: flex;
  flex-flow: row nowrap;

  h3{
    margin: 0;
    line-height: 30px;
    font-size: 16px;
    font-weight: 400;
    padding-left: 5px;
    flex: 1;
  }

  button{
    width: 30px;
    height: 30px;
    margin: 0;
    padding: 0;
    color: #333;
    border: none;
    outline: none;
    background-color: transparent;
  }
}

.stats-plan-list-body{
  max-height: 549px;
  overflow: auto;
}

.stats-plan-map-task{
  padding: 5px;
  border-top: 1px solid #d5d5d5;
  color: #666;

  &:first-child{
    border-top-color: transparent;
  }

  p{
    margin: 0;
    line-height: 24px;
    font-size: 14px;
  }
}

.stats-plan-row{
  display: flex;
	flex-flow: row nowrap;
}

.stats-plan-row-left{
	font-size: 14px;
	width: 70px;
	line-height: 24px;
}

.stats-plan-row-right{
  flex: 1;
	font-size: 14px;
	word-break: break-all;
	line-height: 24px;
}

.stats-plan-map-wrap{
  position: relative;
  height: 100%;
  width: 100%;
}

.plan-map-cluser{
  font-size: 14px;
  text-align: center;
  
  &:hover span{
    color: #fff;
  }

  span{
    // color: transparent;
    color: #fff;
  }
}

.ripple{
  position: relative;
  border-radius: 50%;
  margin: 0 auto;
  background-color: #c41d7f;
  box-shadow: 0 0 4px rgba(0,0,0,.45)
}

.ripple:after,
.ripple:before{
  content: '';
  position: absolute;
  top: 0;
  left: 0;

  width: 100%;
  height: 100%;
  border: 0.5px solid #c41d7f;
  border-radius: 50%;
  box-shadow: 0 0 1px rgba(0, 0, 0, .25)
}

.ripple:before{
  animation:opac 2s linear infinite;
}

.ripple:after{
  animation:opac 2s linear infinite 1s;
}

@keyframes opac{
  0% {
    opacity: 1;
    transform: scale(1);
  }

  100% {
    opacity: 0;
    transform: scale(2);
  }
}
</style>
